package com.gxa.utils;

import com.gxa.pojo.entity.system.Menu;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author lch
 * @Date 2024/2/22 15:52
 * @Description 构建树形数据
 **/
public class AddressTreeUtils {

    // 获取根节点
    public static List<Menu> getRootNode(List<Menu> addressList) {
        List<Menu> rootNode = new ArrayList<>();
        for (Menu address : addressList) {
            //type==0表示根节点
            if (address.getPid() == 0) {
                address.setChildren(getChildren(addressList, address.getId()));
                rootNode.add(address);
            }
        }
        return rootNode;
    }

    // 构建子树
    public static List<Menu> getChildren(List<Menu> addressList, int parentId) {
        List<Menu> children = new ArrayList<>();
        for (Menu address : addressList) {
            //把当前行数据的pid和父节点的id进行比较
            if (address.getPid() == parentId) {
                address.setChildren(getChildren(addressList, address.getId()));
                children.add(address);
            }
        }
        return children;
    }

    //创建树
    public static List<Menu> buildTree(List<Menu> addressList) {
        return getRootNode(addressList);
    }
}
